package com.spider.moudle.browser;

import com.spider.moudle.constant.Constant;
import com.spider.moudle.util.PropertiesUtil;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

/**
 * Created by Linbo Hu on 2017/11/14.
 * 获取浏览器驱动的工具类
 */
public class CommonDriverUtil {

    /**
     * 获取一个浏览器驱动实体
     * @return WebDriver 浏览器驱动实体
     */
    public static WebDriver getDriver() throws Exception {
        String driverType = PropertiesUtil.getVal("browser.driver.type");
        WebDriver webDriver;
        if("CHROME".equals(driverType)) {
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--user-agent="+ Constant.HTTP_USER_AGENT);
            options.addArguments("no-sandbox");
            options.addArguments("disable-extensions");
            options.addArguments("--start-maximized");
            webDriver = new ChromeDriver(options);
        } else if("PHANTOMJS".equals(driverType)) {
            DesiredCapabilities dcaps = new DesiredCapabilities();
            dcaps.setCapability("acceptSslCerts", true);  //ssl证书支持
            dcaps.setCapability("takesScreenshot", true);  //截屏支持
            dcaps.setCapability("cssSelectorsEnabled", true);  //css搜索支持
            dcaps.setJavascriptEnabled(true);  //js支持
            //"Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"
            dcaps.setCapability("phantomjs.page.settings.userAgent", Constant.HTTP_USER_AGENT);
            dcaps.setCapability("phantomjs.page.customHeaders.User-Agent", Constant.HTTP_USER_AGENT);
            webDriver = new PhantomJSDriver(dcaps);
        } else {
            throw new Exception("The value of common.driver.type must be PHANTOMJS or CHROME");
        }
        return webDriver;
    }


}
